package william.list;

/**
 * @author ZhangShenao
 * @date 2024/1/13
 * @description <a href="https://leetcode.cn/problems/linked-list-cycle-ii/description/">...</a>
 */
public class Leetcode142_环形链表2 {
    private class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }


    /**
     * 首先通过快、慢双指针法,判断链表是否有环
     * 如果链表有环,则将慢指针重置到链表头结点,并将快、慢指针每次同时前进一个节点
     * 当快慢指针相遇时,所指向的节点即为开始入环的第一个节点
     */
    public ListNode detectCycle(ListNode head) {
        //边界条件校验
        if (head == null) {
            return null;
        }

        //通过快、慢双指针,判断链表是否有环
        ListNode fast = head;
        ListNode slow = head;
        boolean existCycle = false;

        while (fast.next != null && fast.next.next != null && slow.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {//确认链表有环
                existCycle = true;
                break;
            }
        }

        //如果链表无环,则直接返回null
        if (!existCycle) {
            return null;
        }

        //确认链表成环
        //将slow重置到链表头结点,并将快、慢指针每次同时前进一个节点
        //当快慢指针相遇时,所指向的节点即为开始入环的第一个节点
        slow = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}
